package Message;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import Server.SQLConnection;
import OCSF.*;

public class MessageLogin extends Message{

	
	
	public MessageLogin(String[] str, ConnectionToClient client)
	{
		super(str,client);
	}
	
	public void execute () throws SQLException, IOException
	{
		
		 
		PreparedStatement ps=conn.getConnection().prepareStatement("SELECT * FROM test.Workers WHERE idWorker='"+ str[1] +"' AND Password='"+str[2]+"';");
		PreparedStatement ps2=conn.getConnection().prepareStatement("UPDATE test.Workers SET Connected=? WHERE idWorker=?;");
		PreparedStatement ps3=conn.getConnection().prepareStatement("SELECT * FROM test.customers WHERE idCustomer='"+ str[1] +"' AND Password='"+str[2]+"';");
		ResultSet rs=ps.executeQuery();
		
			if(!rs.next())
			{
				
				ResultSet rs2=ps3.executeQuery();
				if(!rs2.next())
				{
				ps.close();
				rs.close();
				
				client.sendToClient("NotInTheSystem");
				}
				else{
					client.sendToClient("Customer");
				}
			}
			
			else if (rs.getString(6).equals("Worker"))
			{
				if(rs.getInt(7)==1)
					client.sendToClient("MultipleConnect");
				else
				{
				ps2.setInt(1, 1);
				ps2.setString(2, str[1]);
				ps2.executeUpdate();
				client.sendToClient("worker");
				}
				
			}
			else if (rs.getString(6).equals("Service"))
			{
				
				ps2.setInt(1, 1);
				ps2.setString(2, str[1]);
				ps2.executeUpdate();
				client.sendToClient("service");
			}
			else if (rs.getString(6).equals("Manager"))
			{
				ps2.setInt(1, 1);
				ps2.setString(2, str[1]);
				ps2.executeUpdate();
				client.sendToClient("manager");
				
			}
			
	}
}
